import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_class2/3681/accountRelated/account_controller.dart';
import 'package:flutter_class2/common/global.dart';
import 'package:toast/toast.dart';

import '../MainPage.dart';

class CreateAccountPage extends StatelessWidget {
  Widget build(BuildContext context){
    return CreateAccountPageState();
  }
}

class CreateAccountPageState extends StatefulWidget {
  @override
  _CreateAccountPageState createState() => new _CreateAccountPageState();
}

class _CreateAccountPageState extends State<CreateAccountPageState> {

  Global global = new Global();

  bool _passwordVisibleFlag = true;// 控制密码是否为明文字符
  String idStr = '';//先初始化一个值，避免后面长度检测出错
  String phoneNumStr = '';
  String emailStr = '';
  String passwordStr = '';
  String resetPWQuestionStr = '';
  String resetPWAnswerStr = '';

  @override
  Widget build(BuildContext context) {
    var accountDatabaseHelper = new AccountDatabaseHelper();

    final logo = Hero(// 创建hero动画，沟通两个组件之间的tag必须统一
      tag: 'headPic',
      child: CircleAvatar(
        backgroundColor: Colors.transparent,
        radius: 48.0,
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(90)),
          child: Image.asset('images/meng.png'),
        ),
      ),
    );

    final id = TextField(
      autofocus: false,
      maxLines: 1,
      keyboardType: TextInputType.url,
      inputFormatters: [
        LengthLimitingTextInputFormatter(12),
        WhitelistingTextInputFormatter(RegExp('[a-zA-Z0-9]')),//限制输入内容为规定格式
      ],
      decoration: InputDecoration(
        hintText: '必填 - 用户名（限6~12位字母、数字）',
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
        enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
        focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
      ),
      onChanged: (value){
        idStr = value.toString();
      },
    );

    final phoneNum = TextField(
      autofocus: false,
      maxLines: 1,
      keyboardType: TextInputType.number,
      inputFormatters: [
        LengthLimitingTextInputFormatter(11),
        WhitelistingTextInputFormatter(RegExp('[0-9]')),//限制输入内容为规定格式
      ],
      decoration: InputDecoration(
        hintText: '选填 - 手机（仅限中国大陆）',
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
        enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
        focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
      ),
      onChanged: (value){
        phoneNumStr = value;
      },
    );

    final email = TextField(
      autofocus: false,
      maxLines: 1,
      keyboardType: TextInputType.emailAddress,
      inputFormatters: [
        LengthLimitingTextInputFormatter(11),
        WhitelistingTextInputFormatter(RegExp('[a-zA-Z0-9@.]')),//限制输入内容为规定格式
      ],
      decoration: InputDecoration(
        hintText: '选填 - 邮箱（记得加@××.com）',
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
        enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
        focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
      ),
      onChanged: (value){
        emailStr = value;
      },
    );

    final password = TextField(
      autofocus: false,
      maxLines: 1,
      obscureText: _passwordVisibleFlag,
      keyboardType: TextInputType.url,
      inputFormatters: [
        LengthLimitingTextInputFormatter(12),
        WhitelistingTextInputFormatter(RegExp('[a-zA-Z0-9]')),//限制输入内容为规定格式
      ],
      decoration: InputDecoration(
          hintText: '必填 - 密码（限6~12位字母、数字）',
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
          border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
          enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
          focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
          suffixIcon: IconButton(
            icon: Icon(_passwordVisibleFlag ? Icons.visibility : Icons.visibility_off),
            color: Colors.black54,
            onPressed: (){
              setState(() {
                _passwordVisibleFlag = !_passwordVisibleFlag;
              });
            },
          )
      ),
      onChanged: (value){
        passwordStr = value;
      },
    );

    final resetPWQuestion = TextField(
      autofocus: false,
      maxLines: 1,
      keyboardType: TextInputType.url,
      inputFormatters: [
        LengthLimitingTextInputFormatter(16),
      ],
      decoration: InputDecoration(
          hintText: '必填 - 重置密码问题（限16位以下字符）',
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
        enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
        focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
      ),
      onChanged: (value){
        resetPWQuestionStr = value;
      },
    );

    final resetPWAnswer = TextField(
      autofocus: false,
      maxLines: 1,
      keyboardType: TextInputType.url,
      inputFormatters: [
        LengthLimitingTextInputFormatter(16),
      ],
      decoration: InputDecoration(
          hintText: '必填 - 重置密码答案（限16位以下字符）',
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
        enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
        focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
      ),
      onChanged: (value){
        resetPWAnswerStr = value;
      },
    );

    final registerButton = Hero(
        tag: 'loginButton',
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 16.0),
          child: RaisedButton(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            padding: EdgeInsets.all(12),
            color: Colors.black54,
            child: Text('注册', style: TextStyle(color: Colors.white)),
            onPressed: () async{
              if(await accountDatabaseHelper.getAccount(idStr) != null){
                Toast.show('当前用户名已存在，请更改用户名', context);
              }else{
                if(idStr.length >= 6){// 判断用户名是否合理
                  if(passwordStr.length >= 6){// 判断密码是否合理
                    if(resetPWQuestionStr.length != 0){// 判断重置问题是否合理
                      if(resetPWAnswerStr.length != 0){// 判断问题答案是否合理
                        if(phoneNumStr.length != 0){// 若手机号、邮箱一栏不为空，则判断其格式是否正确
                          if(isChinaPhoneLegal(phoneNumStr)){
                            if(emailStr.length != 0){
                              if(isEmailLegal(emailStr)){
                                Toast.show('注册成功', context);
                                successAccount(accountDatabaseHelper, idStr, passwordStr, phoneNumStr, emailStr, resetPWQuestionStr, resetPWAnswerStr);
                                Navigator.pop(context);
                              }else{
                                Toast.show('邮箱有误', context);
                              }
                            }else{
                              Toast.show('注册成功', context);
                              successAccount(accountDatabaseHelper, idStr, passwordStr, phoneNumStr, emailStr, resetPWQuestionStr, resetPWAnswerStr);
                              Navigator.pop(context);
                            }
                          }else{
                            Toast.show('手机号有误', context);
                          }
                        }else{// 手机号、邮箱一栏为空，则不管这两项
                          Toast.show('注册成功', context);
                          successAccount(accountDatabaseHelper, idStr, passwordStr, phoneNumStr, emailStr, resetPWQuestionStr, resetPWAnswerStr);
                          Navigator.pop(context);
                        }
                      }else{
                        Toast.show('请填写重置密码的答案', context);
                      }
                    }else{
                      Toast.show('请填写重置密码的问题', context);
                    }
                  }else{
                    Toast.show('密码长度过短', context);
                  }
                }else{
                  Toast.show('用户名长度过短', context);
                }
              }
            },
          ),
        )
    );



    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,// 防止弹出输入法时内容溢出屏幕
      body: Center(
        child: Container(
          padding: EdgeInsets.only(left: 24.0, right: 24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              logo,
              SizedBox(height: 48.0),
              id,
              SizedBox(height: 12.0),
              phoneNum,
              SizedBox(height: 12.0),
              email,
              SizedBox(height: 12.0),
              password,
              SizedBox(height: 12.0),
              resetPWQuestion,
              SizedBox(height: 12.0),
              resetPWAnswer,
              SizedBox(height: 12.0),
              registerButton,
            ],
          ),
        )
      ),
    );
  }

  ///大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
  /// 此方法中前三位格式有： 13+任意数 * 15+除4的任意数 * 18+除1和4的任意数 * 17+除9的任意数 * 147
  bool isChinaPhoneLegal(String str) {
    return new RegExp('^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$').hasMatch(str);
  }

  /// 检查是否是邮箱格式
  bool isEmailLegal(String input) {
    if (input == null || input.isEmpty) return false;
    return new RegExp("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\$").hasMatch(input);
  }

  Future<void> successAccount(AccountDatabaseHelper db, columnId, password, phoneNum , email , resetPWQuestion , resetPWAnswer) async {
    await db.saveAccount(new Account(columnId, password, phoneNum, email, "", "", 0, 0, 0, resetPWQuestion, resetPWAnswer));
  }

}